﻿using System.Collections.Generic;
using System.Web.Mvc;
using HTB.DevFx;
using Maple.Weixin.MP.Entities;
using Maple.Weixin.MP.MvcExtension;

namespace Maple.Weixin.MP.Web.Controllers
{
    public class WeixinController : Controller
    {
        private readonly IWeixinService weixin = ObjectService.GetObject<IWeixinService>();

        [HttpGet]
        [ActionName("service")]
        [ValidateInput(false)]
        public ActionResult GetService(string signature, string timestamp, string nonce, string echostr) {
            var sign = weixin.GetSignature(timestamp, nonce);
            if (sign == signature)
                return Content(echostr);

            var content = string.Format("timestamp = {0}, nonce = {1}, token = {2}, sign = {3} || signature = {4}",
                timestamp, nonce, ((WeixinService) weixin).Token, sign, signature);
            return Content(content);
        }

        [HttpPost]
        [ActionName("service")]
        [ValidateInput(false)]
        public ActionResult PostService(string signature, string timestamp, string nonce, string echostr) {
            var sign = weixin.GetSignature(timestamp, nonce);
            if (sign != signature) {
                var content =
                    string.Format("timestamp = {0}, nonce = {1}, token = {2}, sign = {3} || signature = {4}",
                        timestamp, nonce, ((WeixinService) weixin).Token, sign, signature);
                return Content(content);
            }
            HTB.DevFx.Log.LogService.WriteLog(Request.RawUrl);
            var responseMessage = weixin.HandleMessage(Request);
            return new WeixinResult(responseMessage);
        }

        // 经测试，微信不会推送成功的消息
        //[HttpGet]
        //[ActionName("sendmsg")]
        //public ActionResult SendTemplateMessage() {
        //    var result = weixin.SendTemplateMessage("ohHjojpMOCsVbwax4ev0mUl9OAYY",
        //        "LbKCG6KSYreWn4msGFE4AIG337cPSnXWAVIdnkJe20s", "", "000000", new Dictionary<string, TemplateMessageData>());
        //    return Json(result, JsonRequestBehavior.AllowGet);
        //}
    }
}
